﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Fall.Core.BaseModels;
using Fall.Core.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Fall.Core.Filters
{
    public class UserFriendlyExceptionFilter : IAsyncExceptionFilter
    {
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            if (context.Exception is UserFriendlyException)
            {
                await HandleAndWrapException(context);
            }
        }
        private static async Task HandleAndWrapException(ExceptionContext context)
        {
            await Task.Run(() =>
            {
                context.HttpContext.Response.StatusCode = 599;
                var myException = (UserFriendlyException)context.Exception;
                context.Result = new ObjectResult(
                    CommonResult<object>.Error("599", new ErrorResult()
                    {
                        Detail = JsonSerializer.Serialize(myException.Data),
                        Message = myException.Message
                    }));
                context.Exception = null; //Handled!
            });
        }
    }
}
